package com.mf.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mf.constant.ConstantBasic;
import com.mf.entity.dto.DtoIncoming;
import com.mf.entity.dto.DtoIncomingDetail;
import com.mf.exception.GraceException;
import com.mf.service.ServiceIncoming;
import com.mf.utils.UtilIdGenerator;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;

import com.mf.entity.dto.DtoSort;
import com.mf.entity.req.search.SearchReqSort;
import com.mf.mapper.MapperSort;
import com.mf.service.ServiceSort;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;


@Service
public class ImplServiceSort extends ServiceImpl<MapperSort, DtoSort> implements ServiceSort {

    @Resource
    private ServiceIncoming serviceIncoming;


    /**
     * 参数查询条件
     */
    @Override
    public LambdaQueryWrapper<DtoSort> fillParams(SearchReqSort params) {
        final LambdaQueryWrapper<DtoSort> wrapper = loadQw();
        if (ObjectUtils.isNotEmpty(params.getKey())) {
            wrapper.and(w -> {
                w.like(DtoSort::getActualWorkFlag, params.getKey())
                        .or()
                        .like(DtoSort::getWorkFlag, params.getKey())
                        .or()
                        .like(DtoSort::getWorkCode, params.getKey())
                        .or()
                        .like(DtoSort::getCustomerName, params.getKey())
                        .or()
                        .like(DtoSort::getCarNumber, params.getKey())
                        .or()
                        .like(DtoSort::getSumWeight, params.getKey());
            });
        }
        wrapper.eq(ObjectUtils.isNotEmpty(params.getCustomerId()), DtoSort::getCustomerId, params.getCustomerId());

        if (ObjectUtils.isNotEmpty(params.getIncomingFlag())) {
            wrapper.apply("JSON_CONTAINS(incoming_flag,{0})", params.getIncomingFlag());
        }
        return wrapper;
    }

    /**
     * 保存
     */
    @Override
    @Transactional
    public DtoSort saveSort(DtoSort dtoSort) {
        // 获取当天的来料单数量
        LambdaQueryWrapper<DtoSort> wrapper = new LambdaQueryWrapper<>();

        final LocalDate toDay = LocalDate.now();

        // 查询当天最新的来料单
        wrapper.between(DtoSort::getCreatedTime, toDay.atStartOfDay(), toDay.atTime(LocalTime.MAX))
                .orderByDesc(DtoSort::getCreatedTime)
                .last("limit 1");
        DtoSort dtoSort1 = getOne(wrapper);

        // 生成工单编号
        if (ObjectUtils.isEmpty(dtoSort1)) {
            dtoSort.setWorkCode(UtilIdGenerator.generateId(ConstantBasic.SORT_CODE_PREFIX,
                    ConstantBasic.CODE_NUMBER_LENGTH, ConstantBasic.START_NUMBER));
        } else {
            dtoSort.setWorkCode(UtilIdGenerator.generateId(ConstantBasic.SORT_CODE_PREFIX,
                    ConstantBasic.CODE_NUMBER_LENGTH, dtoSort1.getWorkCode()));
        }
        this.save(dtoSort);
        return dtoSort;
    }

    /**
     * 根据关联来料单明细，设置车牌号集合,来料标识集合
     */
    @Override
    @Transactional
    public void setCarNo(Integer sortId, List<Integer> incomingIds) {
        final DtoSort dtoSort = getById(sortId);
        if (ObjectUtils.isEmpty(dtoSort)) {
            GraceException.display("工单【" + sortId + "】不存在");
        }
        if (!incomingIds.isEmpty()) {
            final List<DtoIncoming> dtoIncomings = serviceIncoming.listByIds(incomingIds);
            Set<String> carNos = new HashSet<>();
            Set<String> incomingFlags = new HashSet<>();
            for (DtoIncoming dtoIncoming : dtoIncomings) {
                carNos.add(dtoIncoming.getCarNum());
                incomingFlags.add(dtoIncoming.getReceiveCode());
            }
            dtoSort.setCarNumber(new ArrayList<>(carNos));
            dtoSort.setIncomingFlag(new ArrayList<>(incomingFlags));
        } else {
            List<String> defaultCarNos = new ArrayList<>();
            dtoSort.setCarNumber(defaultCarNos);
            dtoSort.setIncomingFlag(defaultCarNos);
        }
        dtoSort.setId(sortId);
        updateById(dtoSort);
    }

}